package com.xxd.gulimail.ware.service.impl;

import com.xxd.common.constant.WareConstant;
import com.xxd.gulimail.ware.entity.PurchaseDetailEntity;
import com.xxd.gulimail.ware.service.PurchaseDetailService;
import com.xxd.gulimail.ware.service.WareSkuService;
import com.xxd.gulimail.ware.vo.MergeVo;
import com.xxd.gulimail.ware.vo.PurchaseDoneVo;
import com.xxd.gulimail.ware.vo.PurchaseItemDeneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxd.common.utils.PageUtils;
import com.xxd.common.utils.Query;

import com.xxd.gulimail.ware.dao.PurchaseDao;
import com.xxd.gulimail.ware.entity.PurchaseEntity;
import com.xxd.gulimail.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService purchaseDetailService;
    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );
        return new PageUtils(page);
    }

    //合并采购单
    @Transactional
    @Override
    public void mergePurchase(MergeVo params) {
        Long purchaseId = params.getPurchaseId();
        if (purchaseId == null){
            //新建一个单子，再合并
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确定采购单状态是0，1才可以
        List<Long> items = params.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(purchaseId);
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        //1.确定当前采购单是新建或者已分配状态
        Collection<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        List<PurchaseEntity> collect = purchaseEntities.stream().filter(obj -> {
            if (obj.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || obj.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
            {
                return true;
            } else {
                return false;
            }
        }).map(obj->{
            obj.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            obj.setUpdateTime(new Date());
            return obj;
        }).collect(Collectors.toList());
        //2.改变采购单的状态
        this.updateBatchById(collect);
        //3.改变采购项的状态
        collect.forEach(obj->{
            List<PurchaseDetailEntity> entities = purchaseDetailService.listByPurchaseId(obj.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(entity.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });
    }

    @Override
    @Transactional
    public void done(PurchaseDoneVo doneVo) {
        //1.改变采购单状态
        Long id = doneVo.getId();

        //2.改变采购项状态
        boolean flag = true;
        ArrayList<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        List<PurchaseItemDeneVo> items = doneVo.getItems();
        for (PurchaseItemDeneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.HASERROE.getCode()){
                flag = false;
            purchaseDetailEntity.setStatus(item.getStatus());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
                //3.将成功采购的入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStoke(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            };
            purchaseDetailEntity.setId(item.getItemId());
            detailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);
        //1.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROE.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

}